package com.example.common.util.security;

import com.example.common.core.exception.ServiceException;
import com.example.common.system.entity.LoginUser;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author chenjf
 * @Date 2022/9/21
 * @Description security工具类
 */
public class SecurityUtil {

    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser() {
        try {
            if (getAuthentication() == null || getAuthentication().getPrincipal() instanceof String) {
                return null;
            }
            return (LoginUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED.value());
        }
    }
    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
}
